<template>
  <view class="page">
    <!-- 顶部标题栏 -->
    <view class="header">
      <view class="header-left" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <view class="header-title">用户管理</view>
      <view class="header-right"></view>
    </view>

    <!-- 搜索和筛选区域 -->
    <view class="search-section">
      <!-- 搜索框 -->
      <view class="search-box">
        <input
          class="search-input"
          v-model="searchKeyword"
          placeholder="搜索用户名、姓名或手机号"
          @input="onSearchInput"
        />
        <text v-if="searchKeyword" class="clear-btn" @click="clearSearch">✕</text>
      </view>

      <!-- 筛选器 -->
      <view class="filter-bar">
        <view class="filter-item">
          <text class="filter-label">角色：</text>
          <picker :value="roleIndex" :range="roleOptions" range-key="label" @change="onRoleChange">
            <view class="picker-box">
              <text>{{ roleOptions[roleIndex].label }}</text>
              <text class="arrow">▼</text>
            </view>
          </picker>
        </view>

        <view class="filter-item">
          <text class="filter-label">状态：</text>
          <picker :value="statusIndex" :range="statusOptions" range-key="label" @change="onStatusChange">
            <view class="picker-box">
              <text>{{ statusOptions[statusIndex].label }}</text>
              <text class="arrow">▼</text>
            </view>
          </picker>
        </view>
      </view>
    </view>

    <!-- 操作按钮区域 -->
    <view class="action-bar">
      <view class="action-info">
        <text v-if="selectedCount > 0" class="selected-count">
          已选择 {{ selectedCount }} 个用户
        </text>
      </view>
      <view class="action-buttons">
        <button
          v-if="selectedCount > 0"
          class="action-btn delete-btn"
          @click="batchDelete"
        >
          批量删除
        </button>
        <button
          v-if="selectedCount > 0 && hasInactiveSelected"
          class="action-btn activate-btn"
          @click="batchActivate"
        >
          批量激活
        </button>
        <button
          v-if="selectedCount > 0 && hasActiveSelected"
          class="action-btn deactivate-btn"
          @click="batchDeactivate"
        >
          批量禁用
        </button>
        <button class="action-btn create-btn" @click="createUser">
          <text class="btn-icon">+</text>
          <text>创建用户</text>
        </button>
      </view>
    </view>

    <!-- 用户列表 -->
    <view class="content">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 空状态 -->
      <view v-else-if="userList.length === 0" class="empty-container">
        <text class="empty-title">暂无用户数据</text>
        <text class="empty-desc">请调整筛选条件或创建新用户</text>
      </view>

      <!-- 用户列表项 -->
      <view v-else class="user-list">
        <view
          v-for="(user, index) in userList"
          :key="user.id"
          class="user-item"
          @click="selectUser(user)"
        >
          <view class="user-info">
            <view class="user-header">
              <view class="user-name">{{ user.realName }}</view>
              <view class="user-role" :class="`role-${user.role}`">{{ getRoleName(user.role) }}</view>
            </view>
            <view class="user-details">
              <text class="detail-item">用户名：{{ user.username }}</text>
              <text class="detail-item" v-if="user.phone">手机：{{ user.phone }}</text>
              <text class="detail-item" v-if="user.email">邮箱：{{ user.email }}</text>
            </view>
          </view>
          <view class="user-meta">
            <view class="user-status" :class="`status-${user.status}`">
              {{ user.status === 'ACTIVE' ? '正常' : '禁用' }}
            </view>
            <view class="user-time">
              {{ formatDate(user.lastLoginTime || user.createdTime) }}
            </view>
          </view>
          <view class="select-checkbox">
            <text class="checkbox" :class="{ checked: selectedUsers.includes(user.id) }">
              {{ selectedUsers.includes(user.id) ? '✓' : '' }}
            </text>
          </view>
        </view>

        <!-- 加载更多 -->
        <view v-if="hasMore" class="load-more" @click="loadMore">
          <text class="load-more-text">加载更多</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { userAPI } from '@/api/user'

// 接口定义
interface User {
  id: string
  username: string
  realName: string
  role: 'ADMIN' | 'SCHOOL_ADMIN' | 'TEACHER' | 'PARENT'
  phone?: string
  email?: string
  avatar?: string
  status: 'ACTIVE' | 'INACTIVE'
  createdTime: string
  lastLoginTime?: string
}

// 状态管理
const loading = ref(false)
const searchKeyword = ref('')
const userList = ref<User[]>([])
const selectedUsers = ref<string[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const hasMore = ref(true)

// 筛选状态
const roleIndex = ref(0)
const statusIndex = ref(0)

// 筛选选项
const roleOptions = [
  { label: '全部角色', value: '' },
  { label: '超级管理员', value: 'ADMIN' },
  { label: '学校管理员', value: 'SCHOOL_ADMIN' },
  { label: '教师', value: 'TEACHER' },
  { label: '家长', value: 'PARENT' }
]

const statusOptions = [
  { label: '全部状态', value: '' },
  { label: '正常', value: 'ACTIVE' },
  { label: '禁用', value: 'INACTIVE' }
]

// 计算属性
const selectedCount = computed(() => selectedUsers.value.length)

const hasInactiveSelected = computed(() => {
  return userList.value.some(user =>
    selectedUsers.value.includes(user.id) && user.status === 'INACTIVE'
  )
})

const hasActiveSelected = computed(() => {
  return userList.value.some(user =>
    selectedUsers.value.includes(user.id) && user.status === 'ACTIVE'
  )
})

// 方法
const goBack = () => {
  uni.navigateBack()
}

const onSearchInput = () => {
  // 防抖搜索
  clearTimeout(searchTimeout)
  searchTimeout = setTimeout(() => {
    refreshList()
  }, 500)
}

const clearSearch = () => {
  searchKeyword.value = ''
  refreshList()
}

const onRoleChange = (e: any) => {
  roleIndex.value = e.detail.value
  refreshList()
}

const onStatusChange = (e: any) => {
  statusIndex.value = e.detail.value
  refreshList()
}

const getRoleName = (role: string): string => {
  const roleMap: Record<string, string> = {
    'ADMIN': '超级管理员',
    'SCHOOL_ADMIN': '学校管理员',
    'TEACHER': '教师',
    'PARENT': '家长'
  }
  return roleMap[role] || role
}

const formatDate = (dateString: string): string => {
  const date = new Date(dateString)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))

  if (days === 0) {
    return '今天'
  } else if (days === 1) {
    return '昨天'
  } else if (days < 7) {
      return `${days}天前`
  } else if (days < 30) {
    return `${Math.floor(days / 7)}周前`
  } else {
    return `${Math.floor(days / 30)}个月前`
  }
}

const selectUser = (user: User) => {
  const index = selectedUsers.value.indexOf(user.id)
  if (index > -1) {
    selectedUsers.value.splice(index, 1)
  } else {
    selectedUsers.value.push(user.id)
  }
}

const createUser = () => {
  uni.navigateTo({
    url: '/pages/admin/user-create'
  })
}

const refreshList = async () => {
  try {
    loading.value = true
    currentPage.value = 1
    hasMore.value = true

    const params = {
      role: roleOptions[roleIndex.value].value,
      status: statusOptions[statusIndex.value].value,
      keyword: searchKeyword.value,
      page: 1,
      pageSize: pageSize.value
    }

    const response = await userAPI.getUsers(params)

    if (response.code === 200 || response.code === 0) {
      userList.value = response.data.content || []
      hasMore.value = userList.value.length === pageSize.value
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'error'
    })
  } finally {
    loading.value = false
  }
}

const loadMore = async () => {
  if (loading.value || !hasMore.value) return

  try {
    loading.value = true
    currentPage.value++

    const params = {
      role: roleOptions[roleIndex.value].value,
      status: statusOptions[statusIndex.value].value,
      keyword: searchKeyword.value,
      page: currentPage.value,
      pageSize: pageSize.value
    }

    const response = await userAPI.getUsers(params)

    if (response.code === 200 || response.code === 0) {
      const newData = response.data.content || []
      userList.value = [...userList.value, ...newData]
      hasMore.value = newData.length === pageSize.value
    }
  } catch (error) {
    console.error('加载更多失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'error'
    })
  } finally {
    loading.value = false
  }
}

const handleUserClick = (user: User) => {
  uni.navigateTo({
    url: `/pages/admin/user-detail?id=${user.id}`
  })
}

const batchDelete = () => {
  if (selectedUsers.value.length === 0) return

  uni.showModal({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          await userAPI.batchDeleteUsers(selectedUsers.value)
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          })
          selectedUsers.value = []
          refreshList()
        } catch (error) {
          console.error('批量删除失败:', error)
          uni.showToast({
            title: '删除失败',
            icon: 'error'
          })
        }
      }
    }
  })
}

const batchActivate = () => {
  const inactiveUsers = selectedUsers.value.filter(userId => {
    const user = userList.value.find(u => u.id === userId)
    return user && user.status === 'INACTIVE'
  })

  if (inactiveUsers.length === 0) return

  batchUpdateStatus(inactiveUsers, 'ACTIVE')
}

const batchDeactivate = () => {
  const activeUsers = selectedUsers.value.filter(userId => {
    const user = userList.value.find(u => u.id === userId)
    return user && user.status === 'ACTIVE'
  })

  if (activeUsers.length === 0) return

  batchUpdateStatus(activeUsers, 'INACTIVE')
}

const batchUpdateStatus = async (userIds: string[], status: 'ACTIVE' | 'INACTIVE') => {
  try {
    await userAPI.batchUpdateUserStatus(userIds, status)
    uni.showToast({
      title: status === 'ACTIVE' ? '激活成功' : '禁用成功',
      icon: 'success'
    })
    selectedUsers.value = []
    refreshList()
  } catch (error) {
    console.error('批量更新状态失败:', error)
    uni.showToast({
      title: '操作失败',
      icon: 'error'
    })
  }
}

let searchTimeout: NodeJS.Timeout

onMounted(() => {
  refreshList()
})
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
}

.header {
  height: 56px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;

  .header-left {
    width: 50px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;

    .back-icon {
      font-size: 20px;
      color: #333;
      font-weight: bold;
    }
  }

  .header-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }

  .header-right {
    width: 50px;
  }
}

.search-section {
  background: #fff;
  padding: 16px;
  margin-bottom: 8px;
}

.search-box {
  position: relative;
  margin-bottom: 12px;

  .search-input {
    width: 100%;
    height: 40px;
    padding: 0 40px 0 12px;
    border: 1px solid #d9d9d9;
    border-radius: 20px;
    font-size: 14px;
    background: #f8f9fa;

    &:focus {
      border-color: #1890ff;
      background: #fff;
    }
  }

  .clear-btn {
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
    width: 24px;
    height: 24px;
    background: #999;
    color: #fff;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
  }
}

.filter-bar {
  display: flex;
  gap: 16px;

  .filter-item {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 8px;

    .filter-label {
      font-size: 14px;
      color: #666;
      white-space: nowrap;
    }

    .picker-box {
      flex: 1;
      height: 32px;
      padding: 0 12px;
      border: 1px solid #d9d9d9;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: #fff;

      .arrow {
        color: #999;
        font-size: 12px;
      }
    }
  }
}

.action-bar {
  background: #fff;
  padding: 12px 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

  .action-info {
    .selected-count {
      font-size: 14px;
      color: #1890ff;
    }
  }

  .action-buttons {
    display: flex;
    gap: 8px;

    .action-btn {
      height: 32px;
      padding: 0 12px;
      border: none;
      border-radius: 16px;
      font-size: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 4px;
    }

    .create-btn {
      background: #1890ff;
      color: #fff;

      .btn-icon {
        font-size: 16px;
      }
    }

    .delete-btn {
      background: #ff4d4f;
      color: #fff;
    }

    .activate-btn {
      background: #52c41a;
      color: #fff;
    }

    .deactivate-btn {
      background: #faad14;
      color: #fff;
    }
  }
}

.content {
  flex: 1;
  padding: 0 16px 16px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;

  .loading-text {
    font-size: 14px;
    color: #999;
  }
}

.empty-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300px;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  text-align: center;

  .empty-title {
    font-size: 16px;
    color: #666;
    margin-bottom: 8px;
  }

  .empty-desc {
    font-size: 14px;
    color: #999;
  }
}

.user-list {
  .user-item {
    background: #fff;
    border-radius: 8px;
    margin-bottom: 8px;
    padding: 16px;
    display: flex;
    align-items: center;
    gap: 12px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

    .select-checkbox {
      width: 24px;
      height: 24px;
      border: 2px solid #d9d9d9;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 4px;

      .checkbox {
        font-size: 14px;
        color: #fff;
        font-weight: bold;
      }

      &.checked {
        background: #1890ff;
        border-color: #1890ff;
      }
    }

    .user-info {
      flex: 1;

      .user-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 4px;

        .user-name {
          font-size: 16px;
          font-weight: 500;
          color: #333;
        }

        .user-role {
          padding: 2px 8px;
          border-radius: 4px;
          font-size: 12px;
          color: #fff;

          &.role-ADMIN {
            background: #1890ff;
          }

          &.role-SCHOOL_ADMIN {
            background: #722ed1;
          }

          &.role-TEACHER {
            background: #52c41a;
          }

          &.role-PARENT {
            background: #fa8c16;
          }
        }
      }

      .user-details {
        .detail-item {
          font-size: 13px;
          color: #666;
          margin-right: 16px;
          display: inline-block;
        }
      }
    }

    .user-meta {
      text-align: right;

      .user-status {
        font-size: 12px;
        padding: 2px 6px;
        border-radius: 4px;
        margin-bottom: 4px;

        &.status-ACTIVE {
          background: #f6ffed;
          color: #52c41a;
          border: 1px solid #b7eb8f;
        }

        &.status-INACTIVE {
          background: #fff2e8;
          color: #fa8c16;
          border: 1px solid #ffd591;
        }
      }

      .user-time {
        font-size: 12px;
        color: #999;
      }
    }
  }

  .load-more {
    text-align: center;
    padding: 16px;
    background: #fff;
    border-radius: 8px;
    margin-top: 8px;

    .load-more-text {
      font-size: 14px;
      color: #1890ff;
    }
  }
}
</style>